<template>
    <div :class="props.className">
        <ul class="relative">
            <div v-if="props.scrollConfig.pullDownRefresh" class="absolute w-full pb-2 text-center text-gray-400" style="transform: translateY(-100%) translateZ(0);">
                <div v-show="state.beforePullDown">
                    <span>松手刷新页面</span>
                </div>
                <div v-show="!state.beforePullDown">
                    <div v-show="state.isPullingDown">
                        <span>刷新中...</span>
                    </div>
                    <div v-show="!state.isPullingDown">
                        <span>已加载最新数据</span>
                    </div>
                </div>
            </div>
            <slot></slot>
            <div class="w-full pb-2">
                <div v-if="!state.isPullUpLoad" class="w-full text-center text-gray-400">
                    已显示全部~
                </div>
                <div v-else class="w-full text-center text-gray-400">加载中...</div>
            </div>
        </ul>
    </div>
</template>
<script setup>
import { toRefs, reactive, getCurrentInstance } from "vue";
const emits = defineEmits(["push", "pull"]);
const prototype = getCurrentInstance().appContext.config.globalProperties;

const props = defineProps({
    className: undefined,
    scrollConfig: {
        type: Object,
        default: {},
    },
});
let state = reactive({
    isPullUpLoad: false,
    // 分页
    pagesData: {
        page: 1,
        size: 10,
    },
    beforePullDown: false,
    isPullingDown: false,
});

function onMountedDown(datas) {
    state.bScrollRef = new prototype.$BScroll(
        "." + props.className,
        props.scrollConfig
    );
    //下拉刷新
    if (props.scrollConfig.pullDownRefresh) {
        state.bScrollRef.on("pullingDown", async () => {
            state.beforePullDown = false;
            state.isPullingDown = true;

            await emits("pull", () => {
                state.isPullingDown = false;
                //恢复到初始状态
                setTimeout(() => {
                    state.bScrollRef.finishPullDown(); //结束下拉刷新行为
                    setTimeout(() => {
                        state.beforePullDown = true;
                        state.bScrollRef.refresh(); //滚动区域的DOM元素结构有变化后，需要执行刷新 refresh()
                    }, 300);
                }, 500);
            });
        });
    }

    //上拉加载更多（分页）
    state.bScrollRef.on("pullingUp", async () => {
        state.isPullUpLoad = true;
        await emits("push", (length) => {
            if (!length) {
                state.isPullUpLoad = false;
                return;
            }
            pullingUpInit();
        });
    });
}
//初始化下拉加载;
function pullingUpInit() {
    setTimeout(() => {
        state.bScrollRef.finishPullUp();
        state.bScrollRef.refresh();
        state.isPullUpLoad = false;
    }, 500);
}
defineExpose({
    onMountedDown,
    pullingUpInit,
});

const {} = toRefs(state);
</script>